package com.example.a2306_shop.minefg

import android.app.ActionBar.LayoutParams
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.PopupMenu
import android.widget.PopupWindow
import android.widget.RatingBar
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.example.a2306_shop.R
import com.example.a2306_shop.adapter.ImgAdapter
import com.example.a2306_shop.adapter.OrderAdapter
import com.example.a2306_shop.databinding.FragmentPayedBinding
import com.example.a2306_shop.databinding.FragmentPayingBinding
import com.example.lib_base.mvvm.BaseFragment
import com.example.lib_base.param.Comment
import com.example.lib_base.param.Refund
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector

class PayedFragment : BaseFragment<FragmentPayedBinding, OrderViewModel>() {
    lateinit var orderAdapter: OrderAdapter
    lateinit var imgAdapter: ImgAdapter//显示上传的图片
    val imgs = mutableListOf<String>()//用来存储上传图片的路径
    override fun initData() {
        viewModel.orderSuccess.observe(this){
            if(it.code==200){
                orderAdapter.data.clear()
                orderAdapter.data.addAll(it.data.list)
                orderAdapter.notifyDataSetChanged()
            }
        }
        viewModel.sendSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                viewModel.order("1",10,1)
            }
        }
        viewModel.deleteSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.refundSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
    }

    override fun initView() {
        orderAdapter = OrderAdapter()
        binding.rv.adapter = orderAdapter
        binding.rv.layoutManager = LinearLayoutManager(context)

        viewModel.order("1",10,1)

        //点催发货，实现评价功能  输入文字  输入图片 最多3个
        orderAdapter.addChildClickViewIds(R.id.order_btn1,R.id.order_more)
        orderAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.order_btn1->{
                    imgAdapter = ImgAdapter()
                    val popupWindow = PopupWindow()
                    popupWindow.width = LayoutParams.MATCH_PARENT
                    popupWindow.height = LayoutParams.WRAP_CONTENT
                        //内容
                    val inflate = LayoutInflater.from(context).inflate(R.layout.diy_window, null)
                    //监听输入框，设置文字数量，当文字超过20时，显示为红色
                    val et = inflate.findViewById<EditText>(R.id.et)
                    et.addTextChangedListener(object:TextWatcher{
                        override fun beforeTextChanged(
                            s: CharSequence?,
                            start: Int,
                            count: Int,
                            after: Int
                        ) {

                        }

                        override fun onTextChanged(
                            s: CharSequence?,
                            start: Int,
                            before: Int,
                            count: Int
                        ) {
                            if(s!=null){
                                if(s.length>=20){
                                    inflate.findViewById<TextView>(R.id.tv_count).setTextColor(Color.RED)
                                }else{
                                    inflate.findViewById<TextView>(R.id.tv_count).setTextColor(Color.BLACK)
                                }
                                inflate.findViewById<TextView>(R.id.tv_count).text = "${s.length}/20"
                            }
                        }

                        override fun afterTextChanged(s: Editable?) {

                        }
                    })
                    val rv = inflate.findViewById<RecyclerView>(R.id.rv)
                    rv.adapter = imgAdapter
                    rv.layoutManager = GridLayoutManager(context,3)
                    //点击上传图片按钮，实现上传图片
                    inflate.findViewById<Button>(R.id.btn_upload).setOnClickListener {
                        PictureSelector.create(this,102).selectPicture()
                    }
                    //点击发送评论按钮，调用接口
                    inflate.findViewById<Button>(R.id.btn_send).setOnClickListener {
                        val comment = Comment()
                        //评论人头像
                        comment.avatar = "http://10.161.9.80:8080/crmebimage/public/user/2025/07/09/9e5abcf7d8ea4cc890dc31b83558905fggvhgsmkhv.png"
                        comment.nickname = "张三"//评论人名称
                        comment.productScore = inflate.findViewById<RatingBar>(R.id.rb).rating.toInt()//评分
                        comment.serviceScore = inflate.findViewById<RatingBar>(R.id.rb).rating.toInt()//评分
                        comment.comment = et.text.toString()//评论内容
                        var pics = ""
                        if(imgs.isNotEmpty()){
                            imgs.forEach {
                                pics+=it
                                pics+=","
                            }
                        }
                        comment.pics = pics//评论图片
                        comment.orderNo = orderAdapter.data[position].orderId //订单id
                        comment.productId = orderAdapter.data[position].orderInfoList[0].productId//商品id
                        viewModel.commentSend(comment)
                        popupWindow.dismiss()//发布成功，让popupwindow关闭
                    }
                    //当popwindow消失时，一定将数据清空
                    popupWindow.setOnDismissListener {
                        imgs.clear()
                    }

                    popupWindow.contentView = inflate
                    popupWindow.isOutsideTouchable = true
                    //获取焦点
                    popupWindow.isFocusable = true
                    //显示
                    popupWindow.showAtLocation(binding.rv,Gravity.BOTTOM,0,0)
                }
                R.id.order_more->{
                    //弹出菜单  删除订单  申请退款
                    val popupMenu = PopupMenu(context,view)
                    popupMenu.inflate(R.menu.menu_order)
                    popupMenu.setOnMenuItemClickListener {
                        when(it.itemId){
                            R.id.orderDelete->{
                                viewModel.orderDelete(orderAdapter.data[position].id)
                                orderAdapter.data.removeAt(position)
                                orderAdapter.notifyItemRemoved(position)
                            }
                            R.id.orderRefund->{
                                //正常情况下应该会有一个弹出框，显示退货信息
                                val refund = Refund()
                                refund.id = orderAdapter.data[position].id
                                refund.text = "收货地址填错了"
                                refund.uni = orderAdapter.data[position].orderId
                                viewModel.orderRefund(refund)
                                orderAdapter.data.removeAt(position)
                                orderAdapter.notifyItemRemoved(position)
                            }
                        }
                        return@setOnMenuItemClickListener true
                    }
                    popupMenu.show()
                }
            }
        }

    }

    override fun getViewModel(): Class<OrderViewModel>  = OrderViewModel::class.java

    override fun getLayout(): Int = R.layout.fragment_payed

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==102&&resultCode==Activity.RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            //如何显示上传的图片  rv接收的  使用list集合存储数据，并绑定到rv上
            imgs.add(pictureBean.path)
            imgAdapter.data.clear()
            imgAdapter.data.addAll(imgs)
            imgAdapter.notifyDataSetChanged()

        }
    }

}